package com.water.tao;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.water.tao.model.Stock;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
@Component
public class SseStockFetcher {
    private static final String SSE_API_URL = "https://query.sse.com.cn/security/stock/queryCompanyAjax.do";
    private static final HttpClient HTTP_CLIENT = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_1_1)
            .followRedirects(HttpClient.Redirect.NORMAL)
            .connectTimeout(Duration.ofSeconds(10))
            .build();
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); // Jackson的核心类

    /**
     * 从上交所 API 抓取指定板块的股票数据。
     * @param marketType 板块类型，例如 "A" (主板A股), "KCB" (科创板), "B" (主板B股), "ALL" (所有)
     * @return 抓取到的股票列表
     */
    public List<Stock> fetchStocks(String marketType) throws IOException, InterruptedException {
        List<Stock> allStocks = new ArrayList<>();
        int pageNum = 1;
        int pageSize = 50;

        System.out.println("开始抓取 " + marketType + " 板块股票...");

        while (true) {
            // 使用 Jackson 的 ObjectNode 构建 JSON 请求体
            ObjectNode payload = OBJECT_MAPPER.createObjectNode();
            payload.put("is Hohk Connect", "0");
            payload.put("productId", marketType);
            payload.put("securityAbbr", "");
            payload.put("sqlId", "COMMON_SSE_ZQPZ_GP_GPLB_ALL");
            payload.put("pageHelp.pageSize", pageSize);
            payload.put("pageHelp.pageNo", pageNum);
            payload.put("pageHelp.beginPage", pageNum);
            payload.put("pageHelp.endPage", pageNum);
            payload.put("pageHelp.cacheSize", 1);
            payload.put("_", System.currentTimeMillis());

            String jsonPayload = OBJECT_MAPPER.writeValueAsString(payload); // 将ObjectNode转换为JSON字符串

            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(SSE_API_URL))
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36")
                    .header("Referer", "https://www.sse.com.cn/assortment/stock/list/share/")
                    //.header("Host", "query.sse.com.cn")
                    .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
                    .build();

            HttpResponse<String> response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() != 200) {
                System.err.println("请求 " + marketType + " 板块数据失败，状态码: " + response.statusCode());
                System.err.println("响应体: " + response.body());
                break;
            }

            // 使用 Jackson 解析 JSON 响应
            JsonNode responseNode = OBJECT_MAPPER.readTree(response.body());
            JsonNode resultListNode = responseNode.get("result");
            JsonNode pageHelpNode = responseNode.get("pageHelp");

            int totalCount = 0;
            if (pageHelpNode != null && pageHelpNode.has("total")) {
                totalCount = pageHelpNode.get("total").asInt();
            }

            if (resultListNode == null || !resultListNode.isArray() || resultListNode.isEmpty()) {
                break; // 没有更多数据
            }

            for (JsonNode stockJson : resultListNode) {
                String code = stockJson.get("SECURITY_CODE").asText();
                String name = stockJson.get("SECURITY_ABBR_A").asText();
                String listDate = stockJson.get("LISTING_DATE").asText();

                String currentMarketType = "";
                if ("A".equals(marketType)) {
                    currentMarketType = "主板A股";
                } else if ("KCB".equals(marketType)) {
                    currentMarketType = "科创板";
                } else if ("B".equals(marketType)) {
                    currentMarketType = "主板B股";
                } else {
                    currentMarketType = "未知";
                }

                allStocks.add(new Stock(code, name, listDate, currentMarketType));
            }

            System.out.printf("  %s 板块：已抓取第 %d 页，当前总数：%d / %d%n", marketType, pageNum, allStocks.size(), totalCount);

            if (resultListNode.size() < pageSize) {
                break;
            }

            pageNum++;
            Thread.sleep(1000); // 增加延时
        }

        System.out.println("完成抓取 " + marketType + " 板块，共抓取 " + allStocks.size() + " 条数据。");
        return allStocks;
    }
}
